﻿using System.Collections.Generic;

namespace TopHero
{
    public class Cell : BaseEntity
    {
        private Game _game;
        public Game game => _game;

        private CellEntity _cellEntity;
        private List<Monster> _monsters;

        private Vector2 _min;
        private Vector2 _max;

        public Cell(Game game, Vector2 min, Vector2 max)
        {
            _game = game;
            _min = min;
            _max = max;
            position = (min + max) / 2;
            _monsters = new List<Monster>();
        }

        public void AddMonster(Monster entity)
        {
            _monsters.Add(entity);
        }

        public List<Monster> GetMonsters()
        {
            return _monsters;
        }

        internal override void Start()
        {
        }

        internal override void Update()
        {
            _cellEntity?.Update();
            foreach (var monster in _monsters)
            {
                monster.Update();
            }

            for (int i = _monsters.Count - 1; i >= 0; i--)
            {
                Monster m = _monsters[i];
                if (m.Dead())
                {
                    _monsters.RemoveAt(i);
                    m.Destroy();
                }
            }
        }

        internal override void Destroy()
        {
            _cellEntity?.Destroy();
            foreach (var monster in _monsters)
            {
                monster.Destroy();
            }
        }

        internal override bool HandleMessage(Telegram telegram)
        {
            if (_cellEntity == null)
            {
                return false;
            }

            return _cellEntity.HandleMessage(telegram);
        }

        internal void Set(CellEntity cellEntity)
        {
            _cellEntity?.Destroy();
            _cellEntity = cellEntity;
            _cellEntity.Start();
        }

        internal void SetEmpty()
        {
            _cellEntity?.Destroy();
            _cellEntity = new CellEntity(_game, this);
            _cellEntity.Start();
        }
    }
}